package com.cheyun.netsalev3.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.databinding.library.baseAdapters.BR
import androidx.lifecycle.ViewModel
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView


/**
 * 通用适配器
 * T：数据类型
 */
open class DefaultAdapter<T>(open var layoutId: Int,
                             open var viewModel: ViewModel?,
                             open var callback: ItemCallback<T>? = ItemCallback()) :
        ListAdapter<T, DefaultAdapter.ViewHolder<T>>(callback!!) {

    constructor(id: Int) : this(id, null)


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder<T> {
        return ViewHolder(DataBindingUtil.inflate(LayoutInflater.from(parent.context), layoutId, parent, false))
    }

    override fun onBindViewHolder(holder: DefaultAdapter.ViewHolder<T>, position: Int) {
        var param = getItem(position)
        holder.apply {
            bind(param, viewModel)
            itemView.tag = param
        }
    }

    class ViewHolder<T>(var binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: T, viewModel: ViewModel?) {
            binding.apply {
                setVariable(BR.item, item)
                setVariable(BR.viewModel, viewModel)
                setVariable(BR.binding, this)
                setVariable(BR.position, adapterPosition)
                executePendingBindings()
            }
        }
    }

    /**
     * 默认的比较器 可以覆盖比较方法
     */
    open class ItemCallback<T> : DiffUtil.ItemCallback<T>() {
        override fun areItemsTheSame(oldItem: T, newItem: T): Boolean {
            return oldItem == newItem
        }

        override fun areContentsTheSame(oldItem: T, newItem: T): Boolean {
            return oldItem == newItem
        }

    }


}

